<template>
  <div class="flex-col h-full">
    <div class="h-8 flex justify-between items-center  mb-1.5 pb-1.5 border-b border-gray-100">
      <div class="flex">
        <span>
        <jb-icon icon="ri:briefcase-4-fill" height="25" color="#000000a3"></jb-icon>
      </span>&nbsp;&nbsp;
        <span class="text-lg">JBoltAI Development Kit</span>
      </div>
      <div class="flex cursor-pointer">
        <span class="icon-box " :class="isPhone?'active':''" @click="isPhone=true">
        <jb-icon icon="ri:device-line" height="20"  color="#000000a3"></jb-icon>
        </span>
        <span class="icon-box"  :class="!isPhone?'active':''" @click="showPC()">
          <jb-icon icon="ri:computer-line" height="20" olor="#000000a3"></jb-icon>
        </span>
      </div>
    </div>
    <n-layout has-sider class="flex-1 shrink-0 box">
      <n-layout class="content" style="display: flex;flex-direction: column" v-show="isPhone">

        <n-tabs class="tabs" type="line" animated>
          <n-tab-pane name="basic" tab="基础">
            <template #tab>
              <jb-icon icon="ri:settings-5-fill" ></jb-icon> &nbsp;
              基础
            </template>
            <Basic style="height: 100%;" :appId="props.appId"></Basic>
          </n-tab-pane>
          <n-tab-pane name="ui" tab="UI布局">
            <template #tab>
              <jb-icon icon="ri:box-3-fill" ></jb-icon> &nbsp;
              UI布局
            </template>
            <ui style="height: 100%" :appId="props.appId" @update-success="handleUpdateSuccess"></ui>
          </n-tab-pane>
          <n-tab-pane name="function" tab="Function">
            <template #tab>
              <jb-icon icon="ri:formula" ></jb-icon> &nbsp;
              Function
            </template>
            <function style="height: 100%" :appId="props.appId"></function>
          </n-tab-pane>
          <n-tab-pane name="knowledge" tab="知识库">
            <template #tab>
              <jb-icon icon="ix:database-filled" ></jb-icon> &nbsp;
              知识库
            </template>
            <Knowledge style="height: 100%" :appId="props.appId"></Knowledge>
          </n-tab-pane>
          <n-tab-pane name="llm" tab="LLM参数">
            <template #tab>
              <jb-icon icon="ri:robot-2-fill" ></jb-icon> &nbsp;
              LLM参数
            </template>
            <llm style="height: 100%" :appId="props.appId"></llm>
          </n-tab-pane>
          <n-tab-pane name="public" tab="发布">
            <template #tab>
              <jb-icon icon="bxs:paper-plane" ></jb-icon> &nbsp;
              发布
            </template>
            <public style="height: 100%" :appId="props.appId"></public>
          </n-tab-pane>
        </n-tabs>


      </n-layout>
      &nbsp; &nbsp; &nbsp; &nbsp;
      <n-layout-sider  collapse-mode="width" :collapsed-width="0" :width="isPhone?550:1300"
                      content-style="border:1px solid #e0e0e6;border-radius:10px;">
        <div style="height: 100%" class="chat_panel" ref="chatContainer">

        </div>
      </n-layout-sider>
    </n-layout>
  </div>
</template>

<script setup>
import {
  onMounted,
  onBeforeUnmount,
  ref,
  watch
} from "vue";
import Basic from "./cpns/basic/index.vue"
import Ui from "./cpns/ui/index.vue"
import Function from "./cpns/function/index.vue"
import Knowledge from "./cpns/knowledge/index.vue"
import Llm from "./cpns/llm/index.vue"
import Public from "./cpns/public/index.vue"
import {
  storeToRefs
} from "pinia";
import {
  useWebSocketStore
} from "@/stores/websocket.js";
import markdownit from "markdown-it";
import {
  JBoltApi
} from "@/service/request/index.js";
import AiChat from "@/components/_builtin/jb-ai-chat/index.js";
import {useMessage} from 'naive-ui'


const props = defineProps({
  appId: String,
  sessionId: String
})
const isPhone=ref(true);


const message = useMessage()
const webSocketStore = storeToRefs(useWebSocketStore())
const md = markdownit({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true
});


const chatContainer = ref(null)
const chatInstance = ref(null)
//默认当前的session对象
const currentSession = ref({})
//默认当前的app对象
const appInfo = ref({
  name: '',
  userAvatar: '',
  showAvatar: false,
  assistantAvatar: '',
})

watch(() => useWebSocketStore().ws.value, (newV) => {

  if (chatContainer.value && newV) {
    chatInstance.value.updateWebSocket(useWebSocketStore().ws.value)
  }
})

watch(() => webSocketStore.ws.value, () => {
  console.debug("websock重连")
  if (chatInstance.value) {
    chatInstance.value.updateWebSocket(webSocketStore.ws.value)
  }
})

watch(() => chatContainer.value, (newV) => {
  // console.log(newV);
  if (newV && !chatInstance.value) {
    loadChatInstance()
  }
})
//监听当前的session对象
watch(() => currentSession.value, (newV) => {
  if (newV) {
    if (chatInstance.value) {
      chatInstance.value.destroy();
    }
    if (chatContainer.value) {
      chatState.value = {
        pageSize: 20,
        hasMore: true
      }
      loadChatInstance()
    }
  }

})
watch(() => appInfo.value, () => {
  console.log("监听appInfo")
  if (chatInstance.value) {
    chatInstance.value.destroy();
  }
  if (chatContainer.value) {
    chatState.value = {
      pager: {
        page: 1,
        pageSize: 20,
      },
      hasMore: true,
    }
    loadChatInstance()
  }
})


const chatState = ref({
  pager: {
    page: 1,
    pageSize: 20,
  },
  hasMore: true,
})


watch(() => props.appId, () => {
  if (chatInstance.value) {
    chatInstance.value.destroy();
  }
  if (chatContainer.value) {
    chatState.value = {
      pager: {
        page: 1,
        pageSize: 20,
      },
      hasMore: true,
    }
    loadChatInstance()
  }
})
function  showPC(){
  isPhone.value=false
}
function loadChatInstance() {
  console.log("传递的值1", appInfo.value.showAvatar)
  console.log("传递的值2", appInfo.value.showAvatar ?? true)
  //初始化aichat
  chatInstance.value = new AiChat(chatContainer.value, {
    // websocketUrl: 'ws://192.168.31.118:8013/ws',
    websocketInstance: webSocketStore.ws.value,
    app: props.appId,
    sessionId: currentSession.value.id,
    global: null,
    showAvatar: appInfo.value.showAvatar ?? true,
    userAvatar: appInfo.value.userAvatar ?? "",
    assistantAvatar: appInfo.value.assistantAvatar ?? "",
    onMsgReceive: (data) => {

    },
    onMsgSend: (msg) => {
      // if (currentSession.value.hasMsg == false) {
      //调用更新sessinoName的方法
      handleUpdateSessionName(currentSession.value.id, msg.data.content.text);
      // }
    },
    onMsgToDelete: async (id) => {
      console.debug("删除消息", id)
      let {
        result
      } = await JBoltApi.get(`/aiAppMessage/delMsgById/${id}`)
      console.log(result, "----")
      if (result.code == 0) {
        message.success("删除成功");
        return true;
      } else {
        message.error("删除失败");
        return false;
      }
    },

    onMarkdownRender: (markdown) => {
      return md.render(markdown);
    },

  },)
}

//更新session
function handleUpdateSessionName(sessionId, msg) {
  var name = msg.substring(0, 20);
  JBoltApi.post('/aiAppSession/update', {
    name: name,
    id: currentSession.value.id,
    appId: props.appId
  }).then(() => {

  });
}

function handleUpdateSuccess() {
  // 在这里更新父组件的状态，比如改变某个变量的值等
  console.log('收到子组件通知，已更新状态');
  getApp();
}

function addSession() {
  JBoltApi.post('/aiAppSession/add', {
    name: '新的App会话',
    appId: props.appId,
    config: {}
  }).then((res) => {
    currentSession.value = res.result.data;
  });
}


function getApp() {
  JBoltApi.get(`/aiApp/getById/${props.appId}`).then((res) => {
    appInfo.value = res.result.data;
    appInfo.value.showAvatar = res.result.data.config.uiConfig.showAvatar;
    appInfo.value.assistantAvatar = res.result.data.config.uiConfig.assistantAvatar;
    appInfo.value.userAvatar = res.result.data.config.uiConfig.userAvatar;
    // 添加会话
  });
}

onMounted(() => {
  getApp();
  addSession();

})
onBeforeUnmount(() => {
  if (chatInstance.value) {
    chatInstance.value.destroy()
  }
})
</script>


<style scoped lang="scss">
.tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;

  :deep(.n-tabs-nav) {
    flex-shrink: 0;
  }

  :deep(.n-tabs-pane-wrapper) {
    flex: 1;
    height: 100%;
  }

  :deep(.n-tab-pane) {
    height: 100%;
    overflow-y: auto;
  }
}

//.content:deep(.n-layout-scroll-container) {
//  display: flex;
//  flex-direction: column;
//  //height: 100%;
//
//}

.chat_panel {
  background: linear-gradient(135deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
  border-radius: 8px;
}

 .icon-box{
   border:  1px solid rgba(121, 121, 121, 0.27);
   display: inline;
   padding: 5px;
 }
 .icon-box:hover{
   background-color: rgba(121, 121, 121, 0.09);

 }
.icon-box:active{
  background-color: rgba(121, 121, 121, 0.09);
}
.active{
  background-color: rgba(121, 121, 121, 0.09);
}
.box :deep(.n-layout-scroll-container){
  justify-content: center;
}
</style>